import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../components/login.vue'
import home from '../components/home.vue'
import welcome from '../components/Welcome.vue'
import users from '../components/user/users.vue'
Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: login },
  {
    path: '/home', component: home, redirect: '/welcome',
    children: [
      { path: '/welcome', component: welcome },
      { path: '/users', component: users }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 在导出路由模块之前，挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 表示要跳转到的页面
  // from 表示从哪一个页面过来
  // next 表示放行 next() next('/login')

  // 如果用户访问的是登录页面，则直接放行
  if (to.path === '/login') {
    return next()
  }

  // 如果不是登录页面，则判断有没有token字符串
  const tokenStr = window.sessionStorage.getItem('token')

  if (!tokenStr) {
    return next('/login')
  }
  next()
})


export default router

